package com.cn.music.view;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.cn.music.model.SendCodeModel;
import com.cn.music.server.Api;
import com.cn.music.server.Constant;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @Auth: 陈彬
 * @Date: 2020/9/28 10:00
 */
public class SendCodeViewModel extends ViewModel {

    private Retrofit retrofit;
    private MutableLiveData<List<SendCodeModel>> codeModel;
    private final static String TAG = "SendCodeViewModel";

    public LiveData<List<SendCodeModel>> loadCodeModel(String phone) {
        if (codeModel == null) {
            codeModel = new MutableLiveData<>();
            responseCodeModel(phone);
        }
        return codeModel;
    }

    private void responseCodeModel(String phone) {

        retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Api api = retrofit.create(Api.class);
        Call<SendCodeModel> call = api.sendCode(phone);
        call.enqueue(new Callback<SendCodeModel>() {
            @Override
            public void onResponse(Call<SendCodeModel> call, Response<SendCodeModel> response) {
                SendCodeModel model = response.body();
                List<SendCodeModel> models = new ArrayList<>();
                models.add(model);
                codeModel.setValue(models);
            }

            @Override
            public void onFailure(Call<SendCodeModel> call, Throwable t) {

            }
        });
    }

}
